package com.yzkj.siot.controller;

import com.yzkj.siot.annotation.Permission;
import com.yzkj.siot.annotation.WebLog;
import com.yzkj.siot.base.BaseController;
import com.yzkj.siot.context.CurUserCtx;
import com.yzkj.siot.domain.TenantDeviceData;
import com.yzkj.siot.dto.DeviceDataDTO;
import com.yzkj.siot.exp.BizExp;
import com.yzkj.siot.facade.DeviceDataFacade;
import com.yzkj.siot.type.ApiType;
import com.yzkj.siot.type.PermissionType;
import com.yzkj.siot.vo.DeviceDataSummaryVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 设备数据 前端控制器
 * </p>
 *
 * @author skye
 * @since 2021-11-07
 */
@Validated
@RestController
@RequestMapping("/deviceData")
public class DeviceDataController extends BaseController {

	@Autowired
	DeviceDataFacade facade;

	@WebLog(type = ApiType.READ)
	@Permission(type = PermissionType.TENANT)
	@GetMapping("exportExcel")
	public Boolean exportExcel(@RequestParam int productId, @RequestParam int productDataId, @RequestParam int deviceId) {

		Integer tenantId = CurUserCtx.get().getTenantId();
		String sendTo = CurUserCtx.get().getUserEmail();

		return facade.exportExcel(tenantId, sendTo,productId, productDataId, deviceId);
	}

	/**
	 * 获取某部分设备的实时数据
	 *
	 * @param deviceId  设备id
	 * @param productId 产品id
	 */
	@WebLog(type = ApiType.READ)
	@Permission(type = PermissionType.TENANT)
	@GetMapping("queryListRealTime")
	public List<TenantDeviceData> queryListRealTime(@RequestParam int deviceId, @RequestParam int productId) {

		return this.facade.queryListRealTime(deviceId, productId);
	}

	@PostMapping("pushData")
	@WebLog(type = ApiType.SAVE_OR_UPDATE)
	@Permission(type = PermissionType.ANY)
	public Boolean pushData(@RequestBody DeviceDataDTO deviceDataDTO) {

		return this.facade.pushData(deviceDataDTO);
	}

	/**
	 * 获取设备数据统计值
	 *
	 * @param timeGranularity 时间间隔粒度(分钟)
	 * @param productDataId   数据解析协议Id
	 * @param startTime       时间区间-开始
	 * @param endTime         时间区间-结束
	 */
	@WebLog(type = ApiType.READ)
	@Permission(type = PermissionType.TENANT)
	@GetMapping("querySummary")
	public List<DeviceDataSummaryVO> querySummary(Integer timeGranularity, Integer productDataId, String startTime,
			String endTime) {

		if (timeGranularity == null || timeGranularity <= 0) {
			throw new BizExp("时间粒度不得小于等于0");
		}

		return facade.querySummary(timeGranularity, productDataId, startTime, endTime);
	}
}
